{% extends "base.html" %}

{% block title %}系统日志 - DHCP代理管理系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">
        <i class="bi bi-journal-text"></i>
        系统日志
    </h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <button type="button" class="btn btn-sm btn-outline-primary" onclick="refreshLogs()">
                <i class="bi bi-arrow-clockwise"></i> 刷新
            </button>
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearLogs()">
                <i class="bi bi-trash"></i> 清除
            </button>
        </div>
        <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="autoRefresh" checked>
            <label class="form-check-label" for="autoRefresh">自动刷新</label>
        </div>
    </div>
</div>

<!-- 日志过滤控制 -->
<div class="card mb-4">
    <div class="card-body">
        <div class="row g-3 align-items-center">
            <div class="col-md-3">
                <label class="form-label">日志级别</label>
                <select class="form-select" id="logLevelFilter" onchange="filterLogs()">
                    <option value="all">所有级别</option>
                    <option value="INFO">INFO</option>
                    <option value="WARNING">WARNING</option>
                    <option value="ERROR">ERROR</option>
                    <option value="DEBUG">DEBUG</option>
                </select>
            </div>
            <div class="col-md-5">
                <label class="form-label">关键词搜索</label>
                <input type="text" class="form-control" id="logSearch" placeholder="输入关键词搜索..." oninput="filterLogs()">
            </div>
            <div class="col-md-2">
                <label class="form-label">显示条数</label>
                <select class="form-select" id="logLimit" onchange="filterLogs()">
                    <option value="50">最近50条</option>
                    <option value="100">最近100条</option>
                    <option value="200">最近200条</option>
                    <option value="500">最近500条</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">&nbsp;</label>
                <button type="button" class="btn btn-outline-secondary w-100" onclick="exportLogs()">
                    <i class="bi bi-download"></i> 导出
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 日志统计 -->
<div class="row mb-4">
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="card bg-primary text-white">
            <div class="card-body py-3">
                <div class="d-flex align-items-center">
                    <div class="flex-grow-1">
                        <div class="small">INFO</div>
                        <div class="h5 mb-0" id="infoCount">0</div>
                    </div>
                    <div class="flex-shrink-0">
                        <i class="bi bi-info-circle fs-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="card bg-warning text-dark">
            <div class="card-body py-3">
                <div class="d-flex align-items-center">
                    <div class="flex-grow-1">
                        <div class="small">WARNING</div>
                        <div class="h5 mb-0" id="warningCount">0</div>
                    </div>
                    <div class="flex-shrink-0">
                        <i class="bi bi-exclamation-triangle fs-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="card bg-danger text-white">
            <div class="card-body py-3">
                <div class="d-flex align-items-center">
                    <div class="flex-grow-1">
                        <div class="small">ERROR</div>
                        <div class="h5 mb-0" id="errorCount">0</div>
                    </div>
                    <div class="flex-shrink-0">
                        <i class="bi bi-x-circle fs-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="card bg-secondary text-white">
            <div class="card-body py-3">
                <div class="d-flex align-items-center">
                    <div class="flex-grow-1">
                        <div class="small">DEBUG</div>
                        <div class="h5 mb-0" id="debugCount">0</div>
                    </div>
                    <div class="flex-shrink-0">
                        <i class="bi bi-bug fs-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="card bg-dark text-white">
            <div class="card-body py-3">
                <div class="d-flex align-items-center">
                    <div class="flex-grow-1">
                        <div class="small">总计</div>
                        <div class="h5 mb-0" id="totalCount">0</div>
                    </div>
                    <div class="flex-shrink-0">
                        <i class="bi bi-list-check fs-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 日志内容 -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">
            <i class="bi bi-list-ul"></i> 日志内容
        </h5>
        <small class="text-muted" id="logCount">正在加载...</small>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover table-sm mb-0" id="logsTable">
                <thead class="table-light">
                    <tr>
                        <th width="150">时间</th>
                        <th width="100">级别</th>
                        <th width="150">记录器</th>
                        <th>消息</th>
                    </tr>
                </thead>
                <tbody id="logsTableBody">
                    <tr>
                        <td colspan="4" class="text-center text-muted py-4">
                            <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                            正在加载日志...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let allLogs = [];
let autoRefreshInterval = null;

document.addEventListener('DOMContentLoaded', function() {
    refreshLogs();
    setupAutoRefresh();
    
    // 设置自动刷新开关事件
    document.getElementById('autoRefresh').addEventListener('change', function() {
        if (this.checked) {
            setupAutoRefresh();
        } else {
            clearInterval(autoRefreshInterval);
            autoRefreshInterval = null;
        }
    });
});

function setupAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
    }
    autoRefreshInterval = setInterval(refreshLogs, 3000);
}

async function refreshLogs() {
    try {
        const response = await fetch('/api/logs');
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error);
        }
        
        allLogs = data.logs;
        filterLogs();
        
    } catch (error) {
        console.error('获取日志失败:', error);
        document.getElementById('logsTableBody').innerHTML = `
            <tr>
                <td colspan="4" class="text-center text-danger py-4">
                    <i class="bi bi-exclamation-triangle"></i><br>
                    加载失败: ${error.message}
                </td>
            </tr>
        `;
    }
}

function filterLogs() {
    const levelFilter = document.getElementById('logLevelFilter').value;
    const searchFilter = document.getElementById('logSearch').value.toLowerCase();
    const limit = parseInt(document.getElementById('logLimit').value);
    
    let filteredLogs = allLogs;
    
    // 按级别过滤
    if (levelFilter !== 'all') {
        filteredLogs = filteredLogs.filter(log => log.level === levelFilter);
    }
    
    // 按关键词搜索
    if (searchFilter) {
        filteredLogs = filteredLogs.filter(log => 
            (log.message && log.message.toLowerCase().includes(searchFilter)) ||
            (log.logger && log.logger.toLowerCase().includes(searchFilter))
        );
    }
    
    // 限制数量
    filteredLogs = filteredLogs.slice(-limit);
    
    updateLogsTable(filteredLogs);
    updateLogStats(filteredLogs);
}

function updateLogsTable(logs) {
    const tbody = document.getElementById('logsTableBody');
    
    if (logs.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="4" class="text-center text-muted py-4">
                    <i class="bi bi-search"></i><br>
                    没有找到匹配的日志
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = logs.map(log => {
        const levelClass = getLogLevelClass(log.level);
        const timestamp = log.timestamp || (log.raw ? log.raw.split(' - ')[0] : '');
        const logger = log.logger || (log.raw ? log.raw.split(' - ')[1] : '');
        const message = log.message || (log.raw ? log.raw.split(' - ').slice(3).join(' - ') : '');
        
        return `
            <tr>
                <td class="text-muted small">${timestamp}</td>
                <td>
                    <span class="badge ${levelClass}">${log.level}</span>
                </td>
                <td class="text-muted small">${logger}</td>
                <td class="log-message">${escapeHtml(message)}</td>
            </tr>
        `;
    }).join('');
    
    document.getElementById('logCount').textContent = `显示 ${logs.length} 条日志`;
    
    // 自动滚动到底部
    tbody.parentNode.scrollTop = tbody.parentNode.scrollHeight;
}

function updateLogStats(logs) {
    const stats = {
        INFO: 0,
        WARNING: 0,
        ERROR: 0,
        DEBUG: 0,
        TOTAL: logs.length
    };
    
    logs.forEach(log => {
        if (stats[log.level] !== undefined) {
            stats[log.level]++;
        }
    });
    
    document.getElementById('infoCount').textContent = stats.INFO;
    document.getElementById('warningCount').textContent = stats.WARNING;
    document.getElementById('errorCount').textContent = stats.ERROR;
    document.getElementById('debugCount').textContent = stats.DEBUG;
    document.getElementById('totalCount').textContent = stats.TOTAL;
}

function getLogLevelClass(level) {
    const classes = {
        'INFO': 'bg-primary',
        'WARNING': 'bg-warning text-dark',
        'ERROR': 'bg-danger',
        'DEBUG': 'bg-secondary'
    };
    return classes[level] || 'bg-secondary';
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function clearLogs() {
    if (confirm('确定要清除当前显示的日志吗？这不会删除日志文件。')) {
        allLogs = [];
        filterLogs();
    }
}

function exportLogs() {
    // 创建日志文本
    const logText = allLogs.map(log => {
        if (log.raw) {
            return log.raw;
        }
        return `${log.timestamp} - ${log.logger} - ${log.level} - ${log.message}`;
    }).join('\n');
    
    // 创建下载链接
    const blob = new Blob([logText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `dhcp-proxy-logs-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.log`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}
</script>

<style>
.log-message {
    font-family: 'Courier New', monospace;
    font-size: 0.875rem;
    word-break: break-all;
}

.table-responsive {
    max-height: 600px;
    overflow-y: auto;
}

#logsTable thead th {
    position: sticky;
    top: 0;
    background: white;
    z-index: 10;
}
</style>
{% endblock %}
